package com.von.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.TimeUnit;


@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public void set(String key, String value) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value);
    }

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void set(String key, String value, long s) {
        ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value, s, TimeUnit.MILLISECONDS);
    }

    public Set<String> getList(String prefix) {
        return redisTemplate.keys(prefix + "*");
    }

    public String get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    //自增
    public void incr(String key) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        entityIdCounter.getAndIncrement();
    }

    public void expire(String key, long s) {
        redisTemplate.expire(key, s, TimeUnit.MILLISECONDS);
    }

    public Object getValue(String lab, String key) {
        return redisTemplate.opsForHash().get(lab, key);
    }

    public void put(String lab, String key, String value) {
        redisTemplate.opsForHash().put(lab, key, value);
    }

    public long getExpire(String key) {
        return redisTemplate.boundHashOps(key).getExpire();
    }


}
